<template>
  <div class="training-sign-page">
    <!-- 1. 培训班基本信息 -->
    <div class="class-info">
      <span class="info-item">培训班编号：{{ selectionDto ? selectionDto[0].trainingClassCode : '123456' }}</span>
      <span class="info-item">培训班名称：{{ selectionDto ? selectionDto[0].trainingClassName : '安全生产管理人员培训（2025期）' }}</span>
      <span class="info-item">
        交接状态：
        <el-tag :type="handoverStatusTagType">{{ handoverStatus }}</el-tag>
      </span>
    </div>

    <!-- 2. 搜索区域 -->
    <div class="search-form" v-show="showSearch">
      <el-form inline :model="searchForm" class="demo-form-inline" size="small">
        <el-form-item label="姓名" label-width="60px">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入"
            clearable
            @keyup.enter.native="handleSearch"
            style="width: 160px"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" label-width="60px">
          <el-input
            v-model="searchForm.phone"
            placeholder="请输入"
            clearable
            @keyup.enter.native="handleSearch"
            style="width: 180px"
          ></el-input>
        </el-form-item>
        <el-form-item label="证件号" label-width="60px">
          <el-input
            v-model="searchForm.idCard"
            placeholder="请输入"
            clearable
            @keyup.enter.native="handleSearch"
            style="width: 220px"
          ></el-input>
        </el-form-item>
        <el-form-item label="报到状态" label-width="80px">
          <el-select
            v-model="searchForm.reportStatus"
            placeholder="全部"
            clearable
            @change="handleSearch"
            style="width: 140px"
          >
            <el-option label="已报到" value="signed"></el-option>
            <el-option label="未报到" value="unsigned"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleSearch">搜索</el-button>
          <el-button size="small" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 3. 操作按钮区域 -->
    <div class="operation-buttons">
      <!-- 3.1 班级管理组 -->
      <div class="button-group">
        <span class="group-label">班级管理</span>
        <el-button type="primary" size="small" plain @click="handleEditClassInfo" :disabled="!single">编辑班级信息</el-button>
        <el-button type="primary" size="small" plain @click="handleSetClassInfo" :disabled="!single">设置班级信息</el-button>
        <el-button type="primary" size="small" plain @click="handleClassHandover" :disabled="!single">班级交接</el-button>
        <el-button type="primary" size="small" plain @click="handleClassRemarkDialog" :disabled="!single">班级备注</el-button>
        <el-button type="primary" size="small" plain @click="handleClassQrcode" :disabled="!single">班级二维码</el-button>
      </div>

      <!-- 3.2 学员管理组 -->
      <div class="button-group">
        <span class="group-label">学员管理</span>
        <el-button type="primary" size="small" plain @click="handleClassStudents" :disabled="!single">班级学员</el-button>
        <el-button type="primary" size="small" plain @click="handleAddStudent" :disabled="!single">添加学员</el-button>
        <el-button type="danger" size="small" plain @click="handleRemoveStudent" :disabled="multiple">移出学员</el-button>
        <el-button type="primary" size="small" plain @click="handleViewStudentDetail" :disabled="!single">学员详情</el-button>
        <el-button type="primary" size="small" plain @click="handleStudentRemark" :disabled="!single">学员备注</el-button>
      </div>

      <!-- 3.3 过程管理组 -->
      <div class="button-group">
        <span class="group-label">过程管理</span>
        <el-button type="primary" size="small"  plain @click="handleSignIn" :disabled="!single">签到</el-button>
        <el-button type="primary" size="small" plain @click="handleSignInStatus" :disabled="!single">签到情况</el-button>
        <el-button type="primary" size="small" plain @click="handleTrainingReservation" :disabled="!single">预约情况</el-button>
        <el-button type="primary" size="small" plain @click="handleStudentNotice" :disabled="multiple">学员通知</el-button>
        <el-button type="primary" size="small" plain @click="handleClassMaintain" :disabled="!single">班级维护</el-button>
      </div>

      <!-- 3.4 数据导出组 -->
      <div class="button-group">
        <span class="group-label">数据导出</span>
        <el-button type="primary" size="small" plain @click="handleExportClassDetail" :disabled="!single">班级详情导出</el-button>
        <el-button type="primary" size="small" plain @click="handleFeeSettlement" :disabled="!single">费用结算</el-button>
        <el-button type="primary" size="small" plain @click="handleExportFeeSettlement" :disabled="!single">费用结算导出</el-button>
      </div>

      <!-- 3.5 其他操作（靠右） -->
      <div class="button-group right-group">
        <el-button size="small" @click="showSearch = !showSearch">
          {{ showSearch ? '隐藏搜索' : '显示搜索' }}
        </el-button>
        <el-button size="small" @click="handleRefresh">刷新</el-button>
        <el-button size="small" @click="handleToggleColumns">列显隐</el-button>

      </div>
    </div>

    <!-- 4. 标签页切换 -->
    <el-tabs v-model="activeTab" type="card" @tab-click="handleTabClick" size="small">
      <!-- 4.1 班级数据 -->
      <el-tab-pane label="班级数据" name="classData">
        <el-table
          v-loading="loading"
          :data="classTableData"
          border
          style="width: 100%; margin-top: 10px;"
          size="small"
        >
          <el-table-column prop="item" label="项目" width="180"></el-table-column>
          <el-table-column prop="value" label="内容" min-width="200"></el-table-column>
          <el-table-column prop="updateTime" label="更新时间" width="180"></el-table-column>
          <el-table-column prop="operator" label="操作人" width="120"></el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 4.2 学员数据 -->
      <el-tab-pane label="学员数据" name="studentData">
        <el-table
          v-loading="loading"
          :data="studentTableData"
          border
          style="width: 100%; margin-top: 10px;"
          @selection-change="handleSelectionChange('student')"
          size="small"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <!-- 配置化渲染列 -->
          <el-table-column
            v-for="col in studentColumns"
            :key="col.prop"
            :prop="col.prop"
            :label="col.label"
            :width="col.width"
            :show-overflow-tooltip="true"
            v-if="columnsVisible[col.prop] !== false"
          >
            <!-- 状态列特殊处理 -->
            <template #default="scope" v-if="col.prop === 'feeStatus'">
              <el-tag :type="scope.row.feeStatus === '已缴费' ? 'success' : 'danger'">
                {{ scope.row.feeStatus }}
              </el-tag>
            </template>
            <template #default="scope" v-else-if="col.prop === 'fileStatus'">
              <el-tag :type="getFileStatusTagType(scope.row.fileStatus)">
                {{ scope.row.fileStatus }}
              </el-tag>
            </template>
            <template #default="scope" v-else-if="col.prop === 'isCompleted'">
              <el-tag :type="scope.row.isCompleted === '是' ? 'success' : 'warning'">
                {{ scope.row.isCompleted }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 4.3 培训计划 -->
      <el-tab-pane label="培训计划" name="trainingPlan">
        <el-table
          v-loading="loading"
          :data="trainingPlanData"
          border
          style="width: 100%; margin-top: 10px;"
          size="small"
        >
          <el-table-column prop="content" label="培训内容" width="180"></el-table-column>
          <el-table-column prop="time" label="培训时间" width="260"></el-table-column>
          <el-table-column prop="place" label="培训地点" width="160"></el-table-column>
          <el-table-column prop="teacher" label="培训教师" width="120"></el-table-column>
          <el-table-column prop="remark" label="备注" min-width="150"></el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 4.4 实践情况 -->
      <el-tab-pane label="实践情况" name="practice">
        <div class="practice-content">
          <h4 class="section-title">实践安排</h4>
          <el-table
            v-loading="loading"
            :data="practiceTopData"
            border
            style="width: 100%; margin-top: 10px;"
            size="small"
          >
            <el-table-column prop="startTime" label="开始时间" width="160"></el-table-column>
            <el-table-column prop="endTime" label="结束时间" width="160"></el-table-column>
            <el-table-column prop="address" label="培训地址" width="160"></el-table-column>
            <el-table-column prop="limit" label="人数限制" width="100"></el-table-column>
            <el-table-column prop="reserveCount" label="预约人数" width="100"></el-table-column>
            <el-table-column prop="teacher" label="培训教师" width="120"></el-table-column>
            <el-table-column prop="list" label="实操名单" min-width="200"></el-table-column>
          </el-table>

          <h4 class="section-title">学员实践状态</h4>
          <el-table
            v-loading="loading"
            :data="practiceStudentData"
            border
            style="width: 100%; margin-top: 10px;"
            @selection-change="handleSelectionChange('practice')"
            size="small"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="编号" width="80"></el-table-column>
            <el-table-column prop="name" label="姓名" width="80"></el-table-column>
            <el-table-column prop="idCard" label="证件编号" width="180"></el-table-column>
            <el-table-column prop="practiceStatus" label="实践状态" width="120">
              <template #default="scope">
                <el-tag :type="scope.row.practiceStatus === '已实践' ? 'success' : 'info'">
                  {{ scope.row.practiceStatus }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="examStatus" label="考试状态" width="120">
              <template #default="scope">
                <el-tag :type="scope.row.examStatus === '已排考' ? 'success' : 'warning'">
                  {{ scope.row.examStatus }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="registerTime" label="报名时间" width="160"></el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 4.5 签到情况 -->
      <el-tab-pane label="签到情况" name="signInStatus">
        <el-table
          v-loading="loading"
          :data="signInTableData"
          border
          style="width: 100%; margin-top: 10px;"
          @selection-change="handleSelectionChange('signIn')"
          size="small"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="编号" width="80"></el-table-column>
          <el-table-column prop="name" label="姓名" width="80"></el-table-column>
          <el-table-column prop="idCard" label="证件编号" width="180"></el-table-column>
          <!-- 动态渲染签到日期列 -->
          <el-table-column
            v-for="(date, idx) in signDates"
            :key="idx"
            :label="`${date} 签到`"
            width="120"
          >
            <template #default="scope">
              <el-tag :type="scope.row[`sign${idx+1}`] === '已签到' ? 'success' : 'danger'">
                {{ scope.row[`sign${idx+1}`] }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="unsignedCount" label="未签到次数" width="120"></el-table-column>
          <el-table-column prop="remark" label="备注" width="150"></el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 4.6 通知情况 -->
      <el-tab-pane label="通知情况" name="notice">
        <el-table
          v-loading="loading"
          :data="noticeTableData"
          border
          style="width: 100%; margin-top: 10px;"
          size="small"
        >
          <el-table-column prop="index" label="序号" width="60"></el-table-column>
          <el-table-column prop="time" label="通知时间" width="180"></el-table-column>
          <el-table-column prop="channel" label="通知渠道" width="200"></el-table-column>
          <el-table-column prop="content" label="通知内容" min-width="200"></el-table-column>
          <el-table-column prop="person" label="通知人员" width="150"></el-table-column>
          <el-table-column prop="publisher" label="发布人" width="100"></el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button type="text" size="small" @click="handleViewNoticeDetail(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 4.7 考试安排 -->
      <el-tab-pane label="考试安排" name="exam">
        <el-table
          v-loading="loading"
          :data="examArrangementData"
          border
          style="width: 100%; margin-top: 10px;"
          size="small"
        >
          <el-table-column prop="startTime" label="考试开始时间" width="180"></el-table-column>
          <el-table-column prop="endTime" label="考试结束时间" width="180"></el-table-column>
          <el-table-column prop="duration" label="考试时长（分钟）" width="150"></el-table-column>
          <el-table-column prop="address" label="考试地址" width="160"></el-table-column>
          <el-table-column prop="way" label="考试途径" width="150"></el-table-column>
          <el-table-column prop="passScore" label="通过分数" width="120"></el-table-column>
          <el-table-column prop="isPublish" label="即时发布成绩" width="150">
            <template #default="scope">
              <el-tag :type="scope.row.isPublish === '是' ? 'success' : 'info'">
                {{ scope.row.isPublish }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="teacher" label="监考人员" width="120"></el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 4.8 费用结算 -->
      <el-tab-pane label="费用结算" name="fee">
        <el-table
          v-loading="loading"
          :data="feeSettlementData"
          border
          style="width: 100%; margin-top: 10px;"
          size="small"
        >
          <el-table-column prop="index" label="序号" width="60"></el-table-column>
          <el-table-column prop="income" label="收入项目" width="180">
            <template #default="scope">
              <span class="text-success" v-if="scope.row.income">{{ scope.row.income }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="expense" label="支出项目" width="180">
            <template #default="scope">
              <span class="text-danger" v-if="scope.row.expense">{{ scope.row.expense }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="count" label="数量" width="80"></el-table-column>
          <el-table-column prop="price" label="单价（元）" width="100"></el-table-column>
          <el-table-column prop="subtotal" label="小计（元）" width="120">
            <template #default="scope">
              <span :class="scope.row.income ? 'text-success' : 'text-danger'">
                {{ scope.row.subtotal }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" width="150"></el-table-column>
        </el-table>

        <!-- 合计行 -->
        <el-table
          :data="feeTotalData"
          border
          style="width: 100%; margin-top: 10px;"
          size="small"
        >
          <el-table-column prop="totalLabel" label="合计" width="600" align="right">
            <template #default="scope">
              <span class="font-bold">{{ scope.row.totalLabel }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="totalValue" label="金额（元）" width="120">
            <template #default="scope">
              <span class="font-bold text-primary">{{ scope.row.totalValue }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 5. 分页组件 -->
    <div class="pagination" v-if="needPagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        size="small"
      ></el-pagination>
    </div>

    <!-- 6. 班级备注弹窗 -->
    <el-dialog :title="remarkTitle" :visible.sync="remarkVisible" width="600px" append-to-body size="small">
      <el-form
        ref="classRemarkForm"
        :model="remarkForm"
        label-width="80px"
        :rules="classRemarkRules"
      >
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="remarkForm.remarks"
            type="textarea"
            :rows="4"
            placeholder="请输入备注内容"
            style="width: 100%"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注历史">
          <el-table
            :data="remarkHistory"
            border
            style="width: 100%"
            size="small"
          >
            <el-table-column prop="time" label="时间" width="200"></el-table-column>
            <el-table-column prop="operator" label="备注人" width="150"></el-table-column>
            <el-table-column prop="content" label="备注" min-width="300"></el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="remarkVisible = false">取消</el-button>
        <el-button type="primary" size="small" @click="submitClassRemark">提交</el-button>
      </div>
    </el-dialog>

    <!-- 7. 通知详情弹窗 -->
    <el-dialog title="通知详情" :visible.sync="noticeDetailVisible" width="500px" append-to-body size="small">
      <el-form :model="noticeDetailForm" label-width="100px" size="small">
        <el-form-item label="通知时间">
          <el-input v-model="noticeDetailForm.time" disabled class="disabled-input"></el-input>
        </el-form-item>
        <el-form-item label="通知渠道">
          <el-input v-model="noticeDetailForm.channel" disabled class="disabled-input"></el-input>
        </el-form-item>
        <el-form-item label="通知内容">
          <el-input v-model="noticeDetailForm.content" type="textarea" :rows="3" disabled class="disabled-input"></el-input>
        </el-form-item>
        <el-form-item label="通知人员">
          <el-input v-model="noticeDetailForm.person" disabled class="disabled-input"></el-input>
        </el-form-item>
        <el-form-item label="发布人">
          <el-input v-model="noticeDetailForm.publisher" disabled class="disabled-input"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="noticeDetailVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 8. 列显隐弹窗 -->
    <el-dialog title="表格列设置" :visible.sync="columnsDialogVisible" width="400px" append-to-body size="small">
      <el-form :model="columnsVisible" size="small">
        <el-form-item label="学员表格列" v-if="activeTab === 'studentData'">
          <el-checkbox-group v-model="visibleStudentColumns">
            <el-checkbox
              v-for="col in studentColumns"
              :key="col.prop"
              :label="col.prop"
              style="display: block; margin-bottom: 8px;"
            >
              {{ col.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="签到表格列" v-if="activeTab === 'signInStatus'">
          <el-checkbox-group v-model="visibleSignInColumns">
            <el-checkbox label="id" style="display: block; margin-bottom: 8px;">编号</el-checkbox>
            <el-checkbox label="name" style="display: block; margin-bottom: 8px;">姓名</el-checkbox>
            <el-checkbox label="idCard" style="display: block; margin-bottom: 8px;">证件编号</el-checkbox>
            <el-checkbox
              v-for="(date, idx) in signDates"
              :key="idx"
              :label="`sign${idx+1}`"
              style="display: block; margin-bottom: 8px;"
            >
              {{ `${date} 签到` }}
            </el-checkbox>
            <el-checkbox label="unsignedCount" style="display: block; margin-bottom: 8px;">未签到次数</el-checkbox>
            <el-checkbox label="remark" style="display: block; margin-bottom: 8px;">备注</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="columnsDialogVisible = false">取消</el-button>
        <el-button type="primary" size="small" @click="saveColumnsSetting">保存设置</el-button>
      </div>
    </el-dialog>

    <!-- 9. 班级二维码弹窗 -->
    <el-dialog title="班级二维码" :visible.sync="qrCodeOpen" width="300px" append-to-body size="small">
      <div class="qr-code-container" v-if="selectionDto && selectionDto.length > 0">
        <div class="qr-code-info">
          班级：{{ selectionDto[0].trainingClassName }}
        </div>
        <div class="qr-code-image">
          <!-- 实际项目中应替换为真实二维码 -->
          <div class="qr-placeholder">二维码图片</div>
        </div>
        <div class="qr-code-desc">
          学员可扫码进行签到或查看班级信息
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="qrCodeOpen = false">关闭</el-button>
        <el-button type="primary" size="small" @click="downloadQrCode">下载二维码</el-button>
      </div>
    </el-dialog>

    <!-- 10. 学员通知弹窗 -->
    <el-dialog title="发送学员通知" :visible.sync="noticeDialogVisible" width="500px" append-to-body size="small">
      <el-form ref="noticeForm" :model="noticeForm" label-width="100px" size="small" :rules="noticeRules">
        <el-form-item label="通知范围" prop="range">
          <el-radio-group v-model="noticeForm.range" @change="handleNoticeRangeChange">
            <el-radio label="all">全体学员</el-radio>
            <el-radio label="selected">选中的学员</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="通知渠道" prop="sendTypes">
          <el-checkbox-group v-model="noticeForm.sendTypes">
            <el-checkbox label="0">短信</el-checkbox>
            <el-checkbox label="1">系统消息</el-checkbox>
            <el-checkbox label="2">微信公众号</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="通知内容" prop="content">
          <el-input v-model="noticeForm.content" type="textarea" :rows="4" placeholder="请输入通知内容"></el-input>
        </el-form-item>

        <el-form-item label="已选学员" v-if="noticeForm.range === 'selected'">
          <el-tag v-for="id in selectedIds.student" :key="id" closable>{{ id }}</el-tag>
          <div v-if="selectedIds.student.length === 0" class="empty-tip">未选择学员</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="noticeDialogVisible = false">取消</el-button>
        <el-button type="primary" size="small" @click="submitNotice">发送</el-button>
      </div>
    </el-dialog>

    <!-- 11. 费用结算弹窗 -->
    <el-dialog title="费用结算详情" :visible.sync="feeSettlementVisible" width="700px" append-to-body size="small">
      <el-table
        :data="feeSettlementData"
        border
        style="width: 100%; margin-top: 10px;"
        size="small"
      >
        <el-table-column prop="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="income" label="收入项目" width="180">
          <template #default="scope">
            <span class="text-success" v-if="scope.row.income">{{ scope.row.income }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="expense" label="支出项目" width="180">
          <template #default="scope">
            <span class="text-danger" v-if="scope.row.expense">{{ scope.row.expense }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="count" label="数量" width="80"></el-table-column>
        <el-table-column prop="price" label="单价（元）" width="100"></el-table-column>
        <el-table-column prop="subtotal" label="小计（元）" width="120">
          <template #default="scope">
            <span :class="scope.row.income ? 'text-success' : 'text-danger'">
              {{ scope.row.subtotal }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="150"></el-table-column>
      </el-table>

      <el-table
        :data="feeTotalData"
        border
        style="width: 100%; margin-top: 10px;"
        size="small"
      >
        <el-table-column prop="totalLabel" label="合计" width="500" align="right">
          <template #default="scope">
            <span class="font-bold">{{ scope.row.totalLabel }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalValue" label="金额（元）" width="120">
          <template #default="scope">
            <span class="font-bold text-primary">{{ scope.row.totalValue }}</span>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="feeSettlementVisible = false">关闭</el-button>
        <el-button type="primary" size="small" @click="handleExportFeeSettlement">导出结算单</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入时间格式化工具
const formatDate = (date) => {
  if (!(date instanceof Date)) date = new Date(date);
  return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
};

// 生成近3天日期（用于签到列）
const getRecentDates = (count = 3) => {
  return Array.from({ length: count }, (_, i) => {
    const date = new Date();
    date.setDate(date.getDate() - i);
    return formatDate(date);
  }).reverse();
};

export default {
  name: 'TrainingClassPage',
  data() {
    return {
      activeTab: 'studentData', // 当前激活标签页
      showSearch: false, // 搜索栏默认隐藏
      loading: false, // 统一加载状态
      columnsDialogVisible: false, // 列显隐弹窗
      remarkVisible: false, // 备注弹窗
      remarkTitle: "班级备注",
      remarkForm: { remarks: "", foreignId: null },
      remarkHistory: [],
      noticeDetailVisible: false, // 通知详情弹窗
      noticeDialogVisible: false, // 发送通知弹窗
      feeSettlementVisible: false, // 费用结算弹窗
      qrCodeOpen: false, // 二维码弹窗
      noticeDetailVisible: false, // 通知详情弹窗
      noticeDetailForm: {}, // 添加这一行，初始化通知详情表单数据

      // 交接状态
      handoverStatus: '未交接', // 可选：未交接/交接中/已交接

      // 搜索表单
      searchForm: {
        name: '',
        phone: '',
        idCard: '',
        reportStatus: ''
      },

      // 分页参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0, // 总记录数

      // 表格列配置
      studentColumns: [
        { prop: 'id', label: '编号', width: 80 },
        { prop: 'name', label: '姓名', width: 80 },
        { prop: 'idCard', label: '证件编号', width: 180 },
        { prop: 'gender', label: '性别', width: 60 },
        { prop: 'phone', label: '电话', width: 120 },
        { prop: 'company', label: '单位名称', width: 150 },
        { prop: 'registerSource', label: '报名来源', width: 150 },
        { prop: 'trainingType', label: '培训类型', width: 100 },
        { prop: 'feeStatus', label: '缴费状态', width: 100 },
        { prop: 'fileStatus', label: '档案状态', width: 100 },
        { prop: 'fileMissing', label: '档案缺失情况', width: 150 },
        { prop: 'submitStatus', label: '提交状态', width: 100 },
        { prop: 'isCompleted', label: '是否办结', width: 100 },
        { prop: 'registerTime', label: '报名时间', width: 160 },
        { prop: 'remark', label: '备注', width: 150 }
      ],

      // 列显示隐藏配置
      columnsVisible: {
        id: true, name: true, idCard: true, gender: true, phone: true,
        company: true, registerSource: true, trainingType: true,
        feeStatus: true, fileStatus: true, fileMissing: true,
        submitStatus: true, isCompleted: true, registerTime: true, remark: true,
        sign1: true, sign2: true, sign3: true, unsignedCount: true
      },
      visibleStudentColumns: ['id', 'name', 'idCard', 'gender', 'phone', 'company', 'registerSource', 'trainingType', 'feeStatus', 'fileStatus', 'fileMissing', 'submitStatus', 'isCompleted', 'registerTime', 'remark'],
      visibleSignInColumns: ['id', 'name', 'idCard', 'sign1', 'sign2', 'sign3', 'unsignedCount', 'remark'],

      // 签到日期（动态生成近3天）
      signDates: getRecentDates(),

      // 各标签页数据
      classTableData: [], // 班级数据
      studentTableData: [], // 学员数据
      trainingPlanData: [], // 培训计划
      practiceTopData: [], // 实践安排
      practiceStudentData: [], // 学员实践状态
      signInTableData: [], // 签到情况
      noticeTableData: [], // 通知情况
      examArrangementData: [], // 考试安排
      feeSettlementData: [], // 费用结算明细
      feeTotalData: [], // 费用结算合计

      // 通知表单数据
      noticeForm: {
        range: 'all', // all:全体学员, selected:选中的学员
        sendTypes: [], // 0:短信, 1:系统消息, 2:微信公众号
        content: '',
        selectedUsers: []
      },
      noticeRules: {
        sendTypes: [{ type: 'array', required: true, min: 1, message: '请至少选择一种通知渠道', trigger: 'change' }],
        content: [{ required: true, message: '请输入通知内容', trigger: 'blur' }]
      },

      // 选中数据
      selectionDto: null, // 选中的班级/学员数据
      selectedIds: {
        student: [],
        practice: [],
        signIn: []
      }, // 不同表格选中的ID数组

      // 辅助计算属性依赖
      allUsers: [], // 所有学员数据
      memberOptions: [], // 班主任数据源
      TrainingClassList: [], // 班级列表数据
      projectOptions: [], // 项目树数据
      departmentData: [] // 部门树数据
    };
  },
  computed: {
    // 交接状态标签类型
    handoverStatusTagType() {
      switch (this.handoverStatus) {
        case '已交接': return 'success';
        case '交接中': return 'warning';
        case '未交接': return 'danger';
        default: return 'info';
      }
    },

    // 判断当前标签页是否需要分页
    needPagination() {
      return ['studentData', 'signInStatus', 'notice'].includes(this.activeTab);
    },

    // 是否单选（selectionDto长度===1）
    single() {
      return this.selectionDto && this.selectionDto.length === 1;
    },

    // 是否未选中（selectionDto长度===0）
    multiple() {
      return !this.selectionDto || this.selectionDto.length === 0;
    },

    // 状态转换
    statusStr() {
      return function(id) {
        if(id === "0") return "未交接";
        else if(id === "1") return "交接中";
        else if(id === "2") return "已交接";
        else return "交接状态有误";
      };
    },

    // 班级备注表单验证规则
    classRemarkRules() {
      return {
        remarks: [{ required: true, message: '请输入备注内容', trigger: 'blur' }]
      };
    }
  },
  created() {
    this.initData(); // 初始化基础数据
    this.getMembersList(); // 加载班主任数据源
    this.getList(); // 加载班级列表数据
    this.loadCurrentTabData(); // 加载当前标签页数据
  },
  methods: {
    // -------------------------- 1. 通用工具方法 --------------------------
    /**
     * 模拟API请求
     * @param {Function} mockDataFn - 生成模拟数据的函数
     * @returns {Promise}
     */
    mockRequest(mockDataFn) {
      this.loading = true;
      return new Promise((resolve) => {
        setTimeout(() => {
          const data = mockDataFn();
          resolve(data);
          this.loading = false;
        }, 300);
      });
    },

    /**
     * 加载当前激活标签页的数据
     */
    loadCurrentTabData() {
      const loadMap = {
        classData: this.loadClassData,
        studentData: this.loadStudentData,
        trainingPlan: this.loadTrainingPlanData,
        practice: this.loadPracticeData,
        signInStatus: this.loadSignInData,
        notice: this.loadNoticeData,
        exam: this.loadExamArrangementData,
        fee: this.loadFeeSettlementData
      };
      const loadFn = loadMap[this.activeTab];
      if (loadFn) loadFn.call(this);
    },

    /**
     * 格式化当前时间
     */
    formatCurrentTime() {
      return new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    },

    /**
     * 获取档案状态标签类型
     */
    getFileStatusTagType(status) {
      switch (status) {
        case '有档案': return 'success';
        case '档案不全': return 'warning';
        case '无档案': return 'danger';
        default: return 'info';
      }
    },

    /**
     * 树形节点查找
     */
    findNodeById(treeData, id) {
      for (const node of treeData) {
        if (node.id.toString() === id.toString()) return node;
        if (node.children && node.children.length > 0) {
          const found = this.findNodeById(node.children, id);
          if (found) return found;
        }
      }
      return null;
    },

    /**
     * 通用下载方法
     */
    download(url, params, filename) {
      const form = document.createElement('form');
      form.method = 'post';
      form.action = url;
      form.target = '_blank';

      // 拼接参数
      Object.keys(params).forEach(key => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = key;
        input.value = params[key];
        form.appendChild(input);
      });

      document.body.appendChild(form);
      form.submit();
      document.body.removeChild(form);
    },

    // -------------------------- 2. 数据加载方法 --------------------------
    // 加载班级列表（核心方法）
    getList() {
      this.loading = true;
      const params = { ...this.queryParams };
      if (this.dateRange && this.dateRange.length === 2) {
        params.startDate = this.dateRange[0];
        params.endDate = this.dateRange[1];
      }

      // 模拟接口调用
      setTimeout(() => {
        this.TrainingClassList = [
          {
            trainingClassId: '1',
            trainingClassCode: '123456',
            trainingClassName: '安全生产管理人员培训（2025期）',
            classStatus: '0',
            trainingType: '1',
            needExam: '1',
            headTeacher2Name: '张三',
            handoverStatus: '0',
            trainingProject: '1'
          }
        ];

        // 默认选中第一个班级
        this.selectionDto = [this.TrainingClassList[0]];
        this.handoverStatus = this.statusStr(this.TrainingClassList[0].handoverStatus);

        this.total = this.TrainingClassList.length;
        this.loading = false;
      }, 500);
    },

    // 加载班主任数据源
    async getMembersList() {
      try {
        // 模拟接口调用
        setTimeout(() => {
          this.memberOptions = [
            { id: '1', name: '张三' },
            { id: '2', name: '李四' },
            { id: '3', name: '王五' }
          ];
        }, 300);
      } catch (error) {
        console.error("人员数据加载失败：", error);
        this.$message.error("人员信息加载失败，请稍后重试");
      }
    },

    // 初始化基础数据（项目树、部门树）
    async initData() {
      await Promise.all([this.getProjectTree(), this.getDepartmentTree()]);
    },

    // 获取项目树（班级设置依赖）
    getProjectTree() {
      return new Promise(resolve => {
        // 模拟接口调用
        setTimeout(() => {
          this.projectOptions = [
            { id: '1', label: '安全生产培训' },
            { id: '2', label: '消防安全培训' }
          ];
          resolve();
        }, 300);
      });
    },

    // 获取部门树（班级设置依赖）
    getDepartmentTree() {
      return new Promise(resolve => {
        // 模拟接口调用
        setTimeout(() => {
          this.departmentData = [
            { id: '1', label: '培训一部' },
            { id: '2', label: '培训二部' }
          ];
          resolve();
        }, 300);
      });
    },

    // 加载班级数据
    loadClassData() {
      this.mockRequest(() => {
        this.classTableData = [
          { item: '培训班名称', value: '安全生产管理人员培训（2025期）', updateTime: '2025-09-01 10:00:00', operator: '系统' },
          { item: '培训班编号', value: '123456', updateTime: '2025-09-01 10:00:00', operator: '系统' },
          { item: '培训周期', value: '2025-09-10 至 2025-09-20', updateTime: '2025-09-02 15:30:00', operator: '李管理员' },
          { item: '培训地点', value: '一号培训室（3楼）', updateTime: '2025-09-02 15:30:00', operator: '李管理员' },
          { item: '预计人数', value: '30人', updateTime: '2025-09-03 09:10:00', operator: '王助理' },
          { item: '当前人数', value: '28人', updateTime: '2025-09-09 16:45:00', operator: '王助理' }
        ];
      });
    },

    // 加载学员数据
    loadStudentData() {
      this.mockRequest(() => {
        this.studentTableData = [
          { id: '25001', name: '张三', idCard: '110101199001011234', gender: '男', phone: '13800138001', company: '北京XX建筑工程有限公司', registerSource: '企业线上报名', trainingType: '新训', feeStatus: '已缴费', fileStatus: '有档案', fileMissing: '', submitStatus: '已提交', isCompleted: '是', registerTime: '2025-09-01 09:12:34', remark: '无' },
          { id: '25002', name: '李四', idCard: '310101199202025678', gender: '女', phone: '13900139002', company: '上海XX设备制造有限公司', registerSource: '个人线上报名', trainingType: '复训', feeStatus: '已缴费', fileStatus: '有档案', fileMissing: '', submitStatus: '已提交', isCompleted: '是', registerTime: '2025-09-01 10:45:12', remark: '需安排补考' },
          { id: '25003', name: '王五', idCard: '440101198803039012', gender: '男', phone: '13700137003', company: '广州XX电力有限公司', registerSource: '集体线下报名', trainingType: '新训', feeStatus: '已缴费', fileStatus: '档案不全', fileMissing: '体检报告；学历证明', submitStatus: '已提交', isCompleted: '否', registerTime: '2025-09-02 08:30:56', remark: '9月15日前补全档案' },
          { id: '25004', name: '赵六', idCard: '510101199504043456', gender: '男', phone: '13600136004', company: '成都XX运输有限公司', registerSource: '个人线下报名', trainingType: '新训', feeStatus: '未缴费', fileStatus: '无档案', fileMissing: '', submitStatus: '已提交', isCompleted: '否', registerTime: '2025-09-02 14:20:33', remark: '联系财务催缴费用' },
          { id: '25005', name: '孙七', idCard: '610101199305057890', gender: '女', phone: '13500135005', company: '西安XX化工有限公司', registerSource: '企业线上报名', trainingType: '新训', feeStatus: '已缴费', fileStatus: '有档案', fileMissing: '', submitStatus: '已提交', isCompleted: '是', registerTime: '2025-09-03 09:05:47', remark: '无' }
        ];
        this.total = this.studentTableData.length;
      });
    },

    // 加载培训计划数据
    loadTrainingPlanData() {
      this.mockRequest(() => {
        this.trainingPlanData = [
          { content: '安全生产法规解读', time: '2025-09-10 09:00:00 ~ 2025-09-10 12:00:00', place: '一号培训室', teacher: '张教授', remark: '需提前发放法规手册' },
          { content: '安全事故案例分析', time: '2025-09-10 14:00:00 ~ 2025-09-10 17:00:00', place: '一号培训室', teacher: '李工程师', remark: '播放事故视频' },
          { content: '现场安全操作规范', time: '2025-09-11 09:00:00 ~ 2025-09-11 12:00:00', place: '实操场地A', teacher: '王教练', remark: '学员需穿劳保服' },
          { content: '应急救援演练', time: '2025-09-11 14:00:00 ~ 2025-09-11 17:00:00', place: '实操场地B', teacher: '刘教官', remark: '携带应急设备' }
        ];
      });
    },

    // 加载实践情况数据
    loadPracticeData() {
      this.mockRequest(() => {
        this.practiceTopData = [
          { startTime: '2025-09-12 09:00:00', endTime: '2025-09-12 12:00:00', address: '实操场地A', limit: 15, reserveCount: 12, teacher: '王教练', list: '张三；李四；王五；赵六；孙七；周八；吴九；郑十；钱一；冯二；陈三；褚四', remark: '设备已调试' },
          { startTime: '2025-09-12 14:00:00', endTime: '2025-09-12 17:00:00', address: '实操场地A', limit: 15, reserveCount: 16, teacher: '王教练', list: '杨五；朱六；秦七；尤八；许九；何十；吕一；施二；张四；孔五；曹六；严七；华八；金九；魏十；陶一', remark: '需加派一名助教' }
        ];

        this.practiceStudentData = [
          { id: '25001', name: '张三', idCard: '110101199001011234', practiceStatus: '已实践', examStatus: '已排考', registerTime: '2025-09-01 09:12:34' },
          { id: '25002', name: '李四', idCard: '310101199202025678', practiceStatus: '已实践', examStatus: '已排考', registerTime: '2025-09-01 10:45:12' },
          { id: '25003', name: '王五', idCard: '440101198803039012', practiceStatus: '已实践', examStatus: '未排考', registerTime: '2025-09-02 08:30:56' },
          { id: '25004', name: '赵六', idCard: '510101199504043456', practiceStatus: '未实践', examStatus: '未排考', registerTime: '2025-09-02 14:20:33' },
          { id: '25005', name: '孙七', idCard: '610101199305057890', practiceStatus: '已实践', examStatus: '已排考', registerTime: '2025-09-03 09:05:47' }
        ];
      });
    },

    // 加载签到情况数据
    loadSignInData() {
      this.mockRequest(() => {
        this.signInTableData = [
          { id: '25001', name: '张三', idCard: '110101199001011234', sign1: '已签到', sign2: '已签到', sign3: '已签到', unsignedCount: 0, remark: '全勤' },
          { id: '25002', name: '李四', idCard: '310101199202025678', sign1: '已签到', sign2: '未签到', sign3: '已签到', unsignedCount: 1, remark: '第二天请假' },
          { id: '25003', name: '王五', idCard: '440101198803039012', sign1: '已签到', sign2: '已签到', sign3: '未签到', unsignedCount: 1, remark: '第三天迟到' },
          { id: '25004', name: '赵六', idCard: '510101199504043456', sign1: '未签到', sign2: '未签到', sign3: '已签到', unsignedCount: 2, remark: '前两天未到' },
          { id: '25005', name: '孙七', idCard: '610101199305057890', sign1: '已签到', sign2: '已签到', sign3: '已签到', unsignedCount: 0, remark: '全勤' }
        ];
        this.total = this.signInTableData.length;
      });
    },

    // 加载通知情况数据
    loadNoticeData() {
      this.mockRequest(() => {
        this.noticeTableData = [
          { index: 1, time: '2025-09-05 15:30:00', channel: '短信+系统消息', content: '各位学员，安全生产培训将于9月10日正式开始，请提前安排时间参加。', person: '全体学员', publisher: '系统' },
          { index: 2, time: '2025-09-08 10:15:00', channel: '系统消息+微信公众号', content: '培训第一天需携带身份证原件和一寸照片2张，请提前准备。', person: '全体学员', publisher: '李管理员' },
          { index: 3, time: '2025-09-10 18:30:00', channel: '系统消息', content: '明日实操培训请穿劳保鞋和工作服，现场不提供更换衣物。', person: '全体学员', publisher: '王教练' }
        ];
        this.total = this.noticeTableData.length;
      });
    },

    // 加载考试安排数据
    loadExamArrangementData() {
      this.mockRequest(() => {
        this.examArrangementData = [
          { startTime: '2025-09-20 09:00:00', endTime: '2025-09-20 11:00:00', duration: '120', address: '三号机房', way: '机考', passScore: '80', isPublish: '是', teacher: '张监考；李监考' }
        ];
      });
    },

    // 加载费用结算数据
    loadFeeSettlementData() {
      this.mockRequest(() => {
        this.feeSettlementData = [
          { index: 1, income: '培训费', expense: '', count: 28, price: '800', subtotal: '22400', remark: '每人800元' },
          { index: 2, income: '', expense: '教材费', count: 30, price: '50', subtotal: '1500', remark: '含备用2本' },
          { index: 3, income: '', expense: '场地租赁费', count: 10, price: '500', subtotal: '5000', remark: '每天500元' },
          { index: 4, income: '', expense: '教师课酬', count: 4, price: '1500', subtotal: '6000', remark: '每位教师1500元' },
          { index: 5, income: '', expense: '杂费', count: 1, price: '1200', subtotal: '1200', remark: '含饮用水、文具等' }
        ];

        // 计算总收入和总支出
        const totalIncome = this.feeSettlementData.reduce((sum, item) => {
          return item.income ? sum + parseFloat(item.subtotal) : sum;
        }, 0);

        const totalExpense = this.feeSettlementData.reduce((sum, item) => {
          return item.expense ? sum + parseFloat(item.subtotal) : sum;
        }, 0);

        const profit = totalIncome - totalExpense;

        this.feeTotalData = [
          { totalLabel: '总收入', totalValue: totalIncome.toFixed(2) },
          { totalLabel: '总支出', totalValue: totalExpense.toFixed(2) },
          { totalLabel: '净利润', totalValue: profit.toFixed(2) }
        ];
      });
    },

    // -------------------------- 3. 事件处理方法 --------------------------
    // 处理表格选择变化
    handleSelectionChange(type, val) {
      this.selectionDto = val;
      this.selectedIds[type] = val.map(item => item.id);
    },

    // 处理标签页切换
    handleTabClick(tab) {
      this.activeTab = tab.name;
      this.queryParams.pageNum = 1; // 切换标签页重置页码
      this.loadCurrentTabData();
    },

    // 处理搜索
    handleSearch() {
      this.queryParams.pageNum = 1;
      this.loadCurrentTabData();
    },

    // 处理重置
    handleReset() {
      this.searchForm = {
        name: '',
        phone: '',
        idCard: '',
        reportStatus: ''
      };
      this.queryParams.pageNum = 1;
      this.loadCurrentTabData();
    },

    // 处理刷新
    handleRefresh() {
      this.loadCurrentTabData();
    },

    // 处理分页大小变化
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.queryParams.pageNum = 1;
      this.loadCurrentTabData();
    },

    // 处理分页页码变化
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.loadCurrentTabData();
    },

    // 处理列显隐切换
    handleToggleColumns() {
      // 根据当前标签页设置可见列
      if (this.activeTab === 'studentData') {
        this.visibleStudentColumns = Object.keys(this.columnsVisible)
          .filter(key => this.columnsVisible[key] && this.studentColumns.some(col => col.prop === key));
      } else if (this.activeTab === 'signInStatus') {
        this.visibleSignInColumns = Object.keys(this.columnsVisible)
          .filter(key => this.columnsVisible[key] && (key === 'id' || key === 'name' || key === 'idCard' ||
                    key.startsWith('sign') || key === 'unsignedCount' || key === 'remark'));
      }
      this.columnsDialogVisible = true;
    },

    // 保存列显隐设置
    saveColumnsSetting() {
      if (this.activeTab === 'studentData') {
        this.studentColumns.forEach(col => {
          this.columnsVisible[col.prop] = this.visibleStudentColumns.includes(col.prop);
        });
      } else if (this.activeTab === 'signInStatus') {
        ['id', 'name', 'idCard', 'unsignedCount', 'remark'].forEach(key => {
          this.columnsVisible[key] = this.visibleSignInColumns.includes(key);
        });
        this.signDates.forEach((_, idx) => {
          const key = `sign${idx+1}`;
          this.columnsVisible[key] = this.visibleSignInColumns.includes(key);
        });
      }
      this.columnsDialogVisible = false;
    },

    // -------------------------- 4. 班级管理相关方法 --------------------------
    // 编辑班级信息
    handleEditClassInfo() {
      this.$message.info('编辑班级信息功能待实现');
    },

    // 设置班级信息
    handleSetClassInfo() {
      this.$message.info('设置班级信息功能待实现');
    },

    // 班级交接
    handleClassHandover() {
      this.$message.info('班级交接功能待实现');
    },

    // 打开班级备注弹窗
    handleClassRemarkDialog() {
      this.remarkTitle = "班级备注";
      this.remarkForm.foreignId = this.selectionDto[0].trainingClassId;

      // 加载备注历史
      this.mockRequest(() => {
        return [
          { time: '2025-09-01 10:30:00', operator: '系统', content: '培训班创建' },
          { time: '2025-09-03 15:20:00', operator: '李管理员', content: '调整了培训时间' }
        ];
      }).then(data => {
        this.remarkHistory = data;
        this.remarkVisible = true;
      });
    },

    // 提交班级备注
    submitClassRemark() {
      this.$refs.classRemarkForm.validate(valid => {
        if (valid) {
          // 模拟提交
          this.mockRequest(() => {
            // 添加新备注到历史记录
            this.remarkHistory.unshift({
              time: this.formatCurrentTime(),
              operator: '当前用户',
              content: this.remarkForm.remarks
            });
            this.remarkForm.remarks = '';
            return true;
          }).then(() => {
            this.$message.success('备注提交成功');
            this.remarkVisible = false;
          });
        }
      });
    },

    // 班级二维码
    handleClassQrcode() {
      this.qrCodeOpen = true;
    },

    // 下载二维码
    downloadQrCode() {
      this.$message.success('二维码下载成功');
    },

    // 班级维护
    handleClassMaintain() {
      this.$message.info('班级维护功能待实现');
    },

    // -------------------------- 5. 学员管理相关方法 --------------------------
    // 班级学员
    handleClassStudents() {
      this.activeTab = 'studentData';
      this.loadStudentData();
    },

    // 添加学员
    handleAddStudent() {
      this.$message.info('添加学员功能待实现');
    },

    // 移出学员
    handleRemoveStudent() {
      if (this.selectedIds.student.length === 0) {
        this.$message.warning('请先选择要移出的学员');
        return;
      }

      this.$confirm(`确定要将选中的${this.selectedIds.student.length}名学员移出班级吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 模拟移除操作
        this.mockRequest(() => {
          this.studentTableData = this.studentTableData.filter(
            item => !this.selectedIds.student.includes(item.id)
          );
          this.total = this.studentTableData.length;
          this.selectionDto = [];
          this.selectedIds.student = [];
          return true;
        }).then(() => {
          this.$message.success('学员移出成功');
        });
      });
    },

    // 查看学员详情
    handleViewStudentDetail() {
      this.$message.info(`查看学员 ${this.selectionDto[0].name} 的详情`);
    },

    // 学员备注
    handleStudentRemark() {
      this.remarkTitle = `学员【${this.selectionDto[0].name}】备注`;
      this.remarkForm.foreignId = this.selectionDto[0].id;

      // 加载学员备注历史
      this.mockRequest(() => {
        return [
          { time: '2025-09-01 09:15:00', operator: '系统', content: '学员报名' },
          { time: '2025-09-02 16:30:00', operator: '王助理', content: '已缴纳培训费用' }
        ];
      }).then(data => {
        this.remarkHistory = data;
        this.remarkVisible = true;
      });
    },

    // -------------------------- 6. 过程管理相关方法 --------------------------
    // 签到
    handleSignIn() {
      this.$message.info('签到功能待实现');
    },

    // 签到情况
    handleSignInStatus() {
      this.activeTab = 'signInStatus';
      this.loadSignInData();
    },

    // 预约情况
    handleTrainingReservation() {
      this.$message.info('预约情况功能待实现');
    },

    // 处理通知范围变化
    handleNoticeRangeChange(val) {
      if (val === 'selected' && this.selectedIds.student.length === 0) {
        this.$message.warning('请先选择学员');
      }
    },

    // 学员通知
    handleStudentNotice() {
      if (this.selectedIds.student.length === 0) {
        this.noticeForm.range = 'all';
      } else {
        this.noticeForm.range = 'selected';
      }
      this.noticeForm.sendTypes = [];
      this.noticeForm.content = '';
      this.noticeDialogVisible = true;
    },

    // 提交通知
    submitNotice() {
      this.$refs.noticeForm.validate(valid => {
        if (valid) {
          if (this.noticeForm.range === 'selected' && this.selectedIds.student.length === 0) {
            this.$message.warning('请先选择学员');
            return;
          }

          // 模拟发送通知
          this.mockRequest(() => {
            const person = this.noticeForm.range === 'all' ? '全体学员' : `选中的${this.selectedIds.student.length}名学员`;
            const channels = [];
            if (this.noticeForm.sendTypes.includes('0')) channels.push('短信');
            if (this.noticeForm.sendTypes.includes('1')) channels.push('系统消息');
            if (this.noticeForm.sendTypes.includes('2')) channels.push('微信公众号');

            // 添加到通知列表
            this.noticeTableData.unshift({
              index: this.noticeTableData.length + 1,
              time: this.formatCurrentTime(),
              channel: channels.join('+'),
              content: this.noticeForm.content,
              person: person,
              publisher: '当前用户'
            });

            // 更新序号
            this.noticeTableData.forEach((item, idx) => {
              item.index = idx + 1;
            });

            this.total = this.noticeTableData.length;
            return true;
          }).then(() => {
            this.$message.success('通知发送成功');
            this.noticeDialogVisible = false;
          });
        }
      });
    },

    // 查看通知详情
    handleViewNoticeDetail(row) {
      this.noticeDetailForm = { ...row };
      this.noticeDetailVisible = true;
    },

    // -------------------------- 7. 数据导出相关方法 --------------------------
    // 班级详情导出
    handleExportClassDetail() {
      this.download('/api/export/classDetail', {
        trainingClassId: this.selectionDto[0].trainingClassId
      }, `${this.selectionDto[0].trainingClassName}详情.xlsx`);
    },

    // 费用结算
    handleFeeSettlement() {
      if (!this.feeSettlementData.length) {
        this.loadFeeSettlementData().then(() => {
          this.feeSettlementVisible = true;
        });
      } else {
        this.feeSettlementVisible = true;
      }
    },

    // 费用结算导出
    handleExportFeeSettlement() {
      this.download('/api/export/feeSettlement', {
        trainingClassId: this.selectionDto[0].trainingClassId
      }, `${this.selectionDto[0].trainingClassName}费用结算.xlsx`);

      // 如果在弹窗中调用，关闭弹窗
      if (this.feeSettlementVisible) {
        this.feeSettlementVisible = false;
      }
    }
  }
};
</script>

<style scoped>
.training-sign-page {
  padding: 15px;
  background-color: #fff;
  min-height: calc(100vh - 30px);
}

/* 班级信息样式 */
.class-info {
  margin-bottom: 15px;
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
}

.info-item {
  font-size: 14px;
  color: #333;
}

/* 搜索区域样式 */
.search-form {
  margin-bottom: 15px;
  padding: 10px 0;
  border-bottom: 1px solid #e8e8e8;
}

/* 操作按钮样式 */
.operation-buttons {
  margin-bottom: 15px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}
.el-button { padding: 6px 10px; }

.button-group {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 5px 0;
}

.group-label {
  font-size: 14px;
  color: #666;
  padding: 0 5px;
}

.right-group {
  margin-left: auto;
}

/* 分页样式 */
.pagination {
  margin-top: 15px;
  text-align: right;
}

/* 实践情况样式 */
.practice-content {
  padding: 10px 0;
}

.section-title {
  margin: 15px 0 10px;
  font-size: 14px;
  color: #333;
  font-weight: bold;
}

/* 弹窗相关样式 */
.disabled-input {
  background-color: #f5f5f5;
  color: #666;
}

.empty-tip {
  color: #999;
  font-size: 12px;
  margin-top: 5px;
}

/* 二维码样式 */
.qr-code-container {
  text-align: center;
  padding: 20px 0;
}

.qr-code-info {
  margin-bottom: 15px;
  font-weight: bold;
}

.qr-code-image {
  width: 180px;
  height: 180px;
  margin: 0 auto 15px;
  border: 1px solid #e8e8e8;
  display: flex;
  align-items: center;
  justify-content: center;
}

.qr-placeholder {
  color: #999;
  font-size: 14px;
}

.qr-code-desc {
  font-size: 12px;
  color: #666;
}

/* 费用结算样式 */
.text-success {
  color: #52c41a;
}

.text-danger {
  color: #f5222d;
}

.font-bold {
  font-weight: bold;
}
</style>
